﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using XieCan.AspMVC.Mapper;

namespace XieCan.AspMVC.WebApi
{
#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释
    public partial class BaseController : ApiController
#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释
    {
        /// <summary>
        /// 将操作结果进行转化
        /// </summary>
        /// <typeparam name="T">转化之前的类型</typeparam>
        /// <typeparam name="C">转化之后的类型</typeparam>
        /// <param name="result">操作结果</param>
        /// <returns>转化之后的操作结果</returns>
        protected OperateResult<IEnumerable<C>> MapResult<T, C>(OperateResult<IQueryable<T>> result)
            where T : XieCanBase
            where C : XieCanBase
        {
            try
            {
                if (result == null)
                    return OperateResult<IEnumerable<C>>.Failed("获取数据失败");

                if (result.Success)
                {
                    return OperateResult<IEnumerable<C>>.Succeeded(result.Data.MapTo<C>());
                }
                return OperateResult<IEnumerable<C>>.Failed(result.Message);
            }
            catch (System.Exception ex)
            {
                return OperateResult<IEnumerable<C>>.Failed(ex);
            }
        }

        /// <summary>
        /// 将操作结果进行转化
        /// </summary>
        /// <typeparam name="T">转化之前的类型</typeparam>
        /// <typeparam name="C">转化之后的类型</typeparam>
        /// <param name="result">操作结果</param>
        /// <returns>转化之后的操作结果</returns>
        protected OperateResult<C> MapResult<T, C>(OperateResult<T> result)
            where T : XieCanBase
            where C : XieCanBase
        {
            try
            {
                if (result == null)
                    return OperateResult<C>.Failed("获取数据失败");

                if (result.Success)
                {
                    return OperateResult<C>.Succeeded(result.Data.MapTo<C>());
                }
                return OperateResult<C>.Failed(result.Message);
            }
            catch (System.Exception ex)
            {
                return OperateResult<C>.Failed(ex);
            }
        }
    }
}